Brief Full Advanced Search Search Tips
|  |  | To access the contents, click the chapter and section titles. Visual Basic 6 Programming Blue Book: The Most Complete, Hands-On Resource for Writing Programs with Microsoft Visual Basic 6! (Publisher: The Coriolis Group) Author(s): Peter G. Aitken ISBN: 1576102815 Publication Date: 08/01/98 Search this book:
Previous | Table of Contents | Next
#### The ERR Object Much of Visual Basic’s ability to deal with errors comes from the ERR object. Each Visual Basic program automatically has a single ERR object associated with it. ERR has global scope, meaning it can be accessed from anywhere in a program. At any moment, ERR contains (in its properties) information about the most recent error that has occurred. The properties you’ll need most often are these: • Number—A type Long value identifying the specific error that occurred. • Description—A brief text description of the error. • Source—A string identifying the name of the object or application that generated the error. The first two properties of the ERR object provide the same numerical code and text description displayed in the error dialog box when an untrapped error occurs. As such, they do not provide a great deal of information. The value of these properties lies in giving your program access to this information in code, enabling it to determine which error occurred and then to take appropriate action. The Source property is not much use in a self-contained application, because it will return only the name of the Visual Basic project. It is more useful when using external objects, as covered later in the chapter. Let’s look at an example. If a program uses a diskette drive, a common potential error that should be trapped is the absence of a diskette in the drive. Attempting to open a file under these conditions results in error number 71. The error-handling code would look something like Listing 25.2. Listing 25.2 Using the ERR object’s Number property to identify the error.
    Private Sub SaveData()

    Dim f As Long

    On Error GoTo FileError

    f = FreeFile

    Open “a:\junk.dat” For Binary As #f

    ' Code to write data goes here.

    Close #f

    Exit Sub

    FileError:

    If Err.Number = 71 Then
        MsgBox (“Please insert a diskette in drive A:, then click OK”)
        Resume
    End If

    End Sub
If there is no diskette in drive A: when this procedure executes, attempting to execute the Open statement will cause error number 71 to occur. Execution will pass to the FileError label, and the ERR object’s Number property will be tested against the value 71. Because it matches, the program will display a message box prompting the user to insert a diskette. When the user closes the message box, the Resume statement will cause execution to continue with the statement that caused the error—in this case, the Open statement. Because a diskette is now in the drive, the statement will execute with no error. Although the code in Listing 25.2 works, you would not want to place it in a real program. Suppose the user does not have a diskette handy. The program should offer the option of canceling the disk write operation. Listing 25.3 shows an improvement on the previous example, providing the user with the option of inserting a diskette and continuing, or canceling. Listing 25.3 Improved error-handling code offers the user a choice.
    Private Sub SaveData()

    Dim f As Long, Reply As Integer
    Dim msg As String

    On Error GoTo FileError

    f = FreeFile

    Open “a:\junk.dat” For Binary As #f

    ' Data writing code goes here.

    Close #f

    Exit Sub

    FileError:

    If Err.Number = 71 Then
        msg = “Please insert a diskette in drive A:, then click Retry.”
        msg = msg & VbCRLF
        msg = msg & “Or click Cancel to try again later.”
        Reply = MsgBox(msg, vbRetryCancel, “Disk error”)
        If Reply = vbRetry Then
            Resume
        ElseIf Reply = vbCancel Then
            Resume Finish
        End If

        ' Other error handling code goes here.

    Finish:

    End If

    End Sub
Now when error number 71 is trapped, a message box is displayed offering users the choice of inserting a disk immediately or canceling the save operation and trying again later (a desirable option for some situations—if the user happens to be out of diskettes and must go fetch one, for example). If the user selects Retry, the Resume statement is used to re-execute the Open statement. If the user selects Cancel, the Resume label is used to direct execution out of the procedure. While improved over the original, this error-handling code is still incomplete. If a different error occurred, execution would still pass to FileError. The If condition would not be True, however, so the associated statements would not be executed. Instead, execution would leave the procedure, and the error would be left hanging. Does this mean the error-handling code in each procedure must explicitly deal with every single possible error? No, that would be impractical. I’ll show you how to create a more generic error handler later in the chapter. Sometimes, error-handling code will test the value of ERR.Number as soon as the error is trapped (as in the previous example). At other times, the numerical error value will not be tested immediately. When this happens, you retrieve the value of ERR.Number and save it in a regular variable. Why? Remember that the ERR object contains information about the single most recent error. If a second error occurs between the time of the first error and retrieving the value of ERR.Number, you receive the numerical code for the second error; information about the first error is lost. As you might well imagine, Visual Basic has a whole slew of trappable errors. How do you find out about them? Activate the Visual Basic Help system and search for “trappable errors” to receive a list of error message categories, such as OLE Automation Messages and Miscellaneous Messages. Select the desired category for a list of related errors and their numerical codes. Select an individual error message to view more details on the causes and possible remedies (if any) for the error condition. TIP: Message Boxes And Line Breaks Sometimes, the message you want to display in a message box is too long to fit on one line. To break a long message into two or more lines, place vbCRLF in the message at the desired break points. This is a defined constant for the newline character. If you place two of these characters, one after the other, you’ll skip two lines. #### Using On Error Resume Next As I have already mentioned, executing the On Error Resume Next statement is necessary when you want to defer error trapping. If this statement is in effect when an error occurs, execution continues with the statement immediately following the one that caused the error. This type of deferred error trapping is most useful when our program is accessing objects—such as OLE automation objects—because it permits you unambiguously to identify the object that caused the error. The basic sequence of code is as follows: 1. Execute On Error Resume Next. 2. Access or manipulate the OLE automation object. 3. Immediately test Err.Number to see if an error has occurred; if so, handle it. Listing 25.4 illustrates this technique. The code attempts to use the GetObject function to access a nonexistent object. This causes error 432, defined as “File name or class name not found during OLE Automation operation.” The If statement tests for this value in Err.Number, and if it is found, displays a dialog box with a message including the name and source of the error. The error source is obtained from the ERR object’s Source property, which contains the name of the object or application that caused the most recent error. In this example, it will return the name of the Visual Basic project. In other cases, such as passing a nonsupported command to an existing OLE Automation object, the object name will be returned. Finally, the Clear method is executed to clear all of the ERR object’s properties. This ensures that the old information from this error will not “hang around” and be misinterpreted later. The Clear method is invoked automatically whenever an On Error, Resume, Exit Sub, or Exit Function statement is executed. Listing 25.4 Demonstrating deferred error handling when accessing objects.
    Private Sub AccessObject()

    Dim MyObj As Object
    Dim msg As String

    On Error Resume Next    ' Defer error trapping.
    ' Try to start a non-existent object.
    MyObj = GetObject(“MyWord.Basic”)

    ' Test for error 432
    If Err.Number = 432 Then    ' OLE Automation error.

        ' Tell user what happened.
        msg = “An error occurred attempting to open the OLE object!”
        msg = msg & VbCRLF
        msg = msg & “Error source: ” & Err.Source
        msg = msg & VbCRLF & “Error number: ” & Err.Number
        MsgBox (msg)
        ' Clear the Err object properties.
        Err.Clear
    End If

    End Sub
#### Raising Errors When working on your project’s error-handling code, mimicking the occurrence of certain runtime errors is often useful, so you can see exactly how your error-handling routines work. You can mimic errors in code using the ERR object’s Raise method. The syntax is as follows:
    Err.Raise number, source, description, helpfile, helpcontext
The only required argument is number, which is a Long integer that identifies the error. To mimic a specific Visual Basic error, use the number associated with the error, as indicated in the Help information. The other arguments are optional: • source—String expression naming the object or application that generated the error. When setting this property for an object, use the form project.class. If source is not specified, the programmatic ID of the current Visual Basic project is used. • description—String expression describing the error. If unspecified, the value in number is examined. If it can be mapped to a Visual Basic runtime error code, the string that would be returned by the Error function is used as description. If no Visual Basic error corresponds to number, the “Application-defined or object-defined error” message is used. • helpfile—The fully qualified path to the Microsoft Windows Help file in which help on this error can be found. If unspecified, Visual Basic uses the fully qualified drive, path, and file name of the Visual Basic Help file. • helpcontext—The context ID identifying a topic within helpfile that provides help for the error. If omitted, the Visual Basic Help file context ID for the error corresponding to the Number property is used, if it exists. The following line of code, for example, will simulate a “Disk not ready” error:
    Err.Raise 71
TIP: Where Is The Error Statement? Earlier versions of Visual Basic used the Error statement to simulate runtime errors. Error is still supported, but only for purposes of backward compatibility. You should always use the Raise method in new code to simulate errors.
Previous | Table of Contents | Next

| Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.